//
//  Video.swift
//  UGImage
//
//  Created by admin on 2022/5/14.
//

import Foundation
import AVFAudio
import AVFoundation
import TZImagePickerController

public extension AVAsset{
	static let defualPath = UIApplication.KDocumnetPath.appending("/ugvideo")
	/**
	 AVAsset 转mp4
	 */
	 func toMp4(_ exportPreset:String=AVAssetExportPresetHighestQuality,
						topath:String=defualPath,
						filename:String = "/\(Date().timeIntervalSince1970).mp4",
						finesh:@escaping ( _ avasset:String?,_ error:Error?)->()){
		
	
		let compatiblePresets = AVAssetExportSession.exportPresets(compatibleWith: self)
		if compatiblePresets.contains(exportPreset) == false{
			let error = UGImageError(code: -1, msg: "无对应清晰度")
			finesh(nil,error)
			return
		}
		
		if FileManager.default.createPathIfNotExit(topath) == false{
			let error = UGImageError(code: -1, msg: "创建文件夹失败")
			finesh(nil,error)
			return
		}
		guard let exportSession = AVAssetExportSession.init(asset: self, presetName: exportPreset)else{
			let error = UGImageError(code: -1, msg: "初始化转码器失败")
			finesh(nil,error)
			return
		}
		
	 
		let outurl:URL = .init(fileURLWithPath: topath.appending(filename))
	   
		exportSession.outputURL = outurl
		exportSession.outputFileType = .mp4
		exportSession.shouldOptimizeForNetworkUse = true
		exportSession.exportAsynchronously(completionHandler: {
			switch exportSession.status{
			case .completed:
				finesh(filename,nil)
				break
			default:
				let error = UGImageError(code: -1, msg: "error:\(exportSession.status)")
				finesh(nil,error)
				break
			}
		})
		#if DEBUG
         Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { timer in
             log("转mp4 进度：\(exportSession.progress)")
             if exportSession.progress>0.95{
                 timer.invalidate()
             }
         })
		#endif
	}
	
	/**
	 AVAsset 裁剪
	 */
	func cut(star:Float = 0,
					  end:Float,
					  topath:String? = nil,
					  filename:String? = nil,
					  exportPreset:String=AVAssetExportPresetHighestQuality,
					  finesh:@escaping ( _ avasset:URL?,_ error:Error?)->()){

		let topath:String = topath ?? UIApplication.KCachePath.appending("CQCache")
		let filename:String = filename ?? "/cut_\(Date().timeIntervalSince1970).mp4"

		let compatiblePresets = AVAssetExportSession.exportPresets(compatibleWith: self)
		if compatiblePresets.contains(exportPreset) == false{
			let error = UGImageError(code: -1,debugmsg: "无对应清晰度")
			finesh(nil,error)
			return
		}
		if FileManager.default.createPathIfNotExit(topath) == false{
			let error = UGImageError(code: -1,debugmsg: "创建文件夹失败")
			finesh(nil,error)
			return
		}
		guard let exportSession = AVAssetExportSession.init(asset: self, presetName: exportPreset) else{
			let error = UGImageError(code: -1,debugmsg: "初始化转码器失败")
			finesh(nil,error)
			return
		}
		let outurl:URL = .init(fileURLWithPath: topath.appending(filename))
		let durationTime = (end>0) ? CMTime(seconds:Double(end), preferredTimescale:  duration.timescale) : duration
		let startTime = CMTime(seconds:Double(star), preferredTimescale:  duration.timescale)
		let timerange = CMTimeRange(start: startTime, duration: durationTime)
		exportSession.timeRange = timerange

		exportSession.outputURL = outurl
		exportSession.outputFileType = .mp4
		exportSession.shouldOptimizeForNetworkUse = true

		exportSession.exportAsynchronously {
			switch exportSession.status{
			case .completed:
				finesh(outurl,nil)
				break
			default:
				let error = UGImageError(code: -1,debugmsg: "error:\(exportSession.status)")
				finesh(nil,error)
				break
			}
		}
		#if DEBUG
        Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { timer in
            
            log("裁剪视频 进度：\(exportSession.progress)")
            if exportSession.progress>0.95{
                timer.invalidate()
            }
        })
		#endif

	}
	

}




public extension UIImage{

	static let defualPath = UIApplication.KDocumnetPath.appending("/ugvideo")

	static func ug_videofirstImage(url:URL?)->UIImage?{
		guard let url = url else{
			return nil
		}
		
		return TZImageManager.default().getImageWithVideoURL(url)
		
		
	}

    static func ug_videofirstImage(_ name:String?,
								   path:String=defualPath)->UIImage?{

		
		
		guard let name = name else{
			return nil
		}
		if name.hasPrefix("http"){
	
			let url = URL.init(string: name)
			
			return TZImageManager.default().getImageWithVideoURL(url)
		}else{
			let urlstr = "\(path)\(name)"
			let url = URL.init(fileURLWithPath: urlstr)
			
			return TZImageManager.default().getImageWithVideoURL(url)
		}

		
		
	}
}
